package com.hmall.trade.listener;

import com.alibaba.fastjson.JSONObject;
import com.hmall.api.pay.PayClient;
import com.hmall.api.pay.domain.PayOrderDTO;
import com.hmall.api.trade.domain.OrderDetailDTO;
import com.hmall.common.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

/**
 * 订单延迟消息监听器, 用于处理订单超时未支付时取消订单
 *
 * @Author katana
 * @Date 2025/6/23 17:22
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderDelayMessageListener {
    
    private final IOrderService orderService;
    
    private final PayClient payClient;
    
    
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAY_ORDER_QUEUE_NAME),
            exchange = @Exchange(name = MqConstants.DELAY_EXCHANGE_NAME, delayed = "true"),
            key = MqConstants.DELAY_ORDER_KEY
    ))
    public void listenOrderDelay(String delayMsg) {
        JSONObject jsonObject = JSONObject.parseObject(delayMsg);
        log.info("订单延迟消息监听器监听到的延迟消息: {}", delayMsg);
        Long orderId = jsonObject.getLong("orderId");
        // 从delayMsg中获取商品信息,拿到的是json字符串
        // 获取 items 值并处理可能的 null 或类型错误
        String string = jsonObject.getString("items");
        List<OrderDetailDTO> items = string != null ? JSONObject.parseArray(string, OrderDetailDTO.class) : Collections.emptyList();
        
        
        log.info("订单延迟消息监听器监听到延迟消息, 订单id: {}", orderId);
        //1 获取订单
        Order order = orderService.getById(orderId);
        //2 判断订单是否支付成功
        if (order == null || order.getStatus() != 1) {
            //订单不存在或者订单已经支付成功
            return;
        }
        
        // 3.未支付，需要查询支付流水状态
        PayOrderDTO payOrder = payClient.queryByBizOrderNo(orderId);
        // 4.判断是否支付
        if (payOrder != null && payOrder.getStatus() == 3) {
            // 4.1.已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
        } else {
            //4.2.未支付，取消订单，回复库存
            orderService.cancelOrder(orderId, items);
        }
        
        
    }
    
}
